package hn.cch.aspect;

import hn.cch.http.request.HttpReqMsg;
import hn.cch.util.Des3Util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 加密解密切面编程
 */
@Component
@Aspect
@Order(3)
public class CryptAop {
    private Logger logger = LoggerFactory.getLogger(CryptAop.class);

    @Around("execution(* hn.cch.http.api.*.api(..))")
    public Object aop(ProceedingJoinPoint joinPoint) {


        logger.info("CryptAop start");
        Object[] args = joinPoint.getArgs();
        HttpReqMsg httpReqMsg = null;
        byte[] data = null;
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof HttpReqMsg) {
                httpReqMsg = (HttpReqMsg) args[i];
            }
            if (args[i] instanceof byte[]) {
                data = (byte[]) args[i];
            }
        }
        if (data == null) {
            logger.error("CryptAop error");
        }
        byte[] param = Des3Util.crypt(Des3Util.CRYPT.DE, data, Des3Util.key);
        /******************************************************/
        Object object = null;
        try {
            object = joinPoint.proceed(new Object[]{httpReqMsg, param});
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error("CryptAop fail");
        }
        /******************************************************/
        byte[] result = null;
        if (object instanceof byte[]) {
            result = (byte[]) object;
        }

        if (data == null) {
            logger.error("CryptAop error");
        }
        byte[] crypt = Des3Util.crypt(Des3Util.CRYPT.EN, result, Des3Util.key);

        logger.error("CryptAop success");
        return crypt;
    }

}
